
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message {
    public String from;
    public String to;
    public String message;
}


@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private TemplateEngine engine = new TemplateEngine();

    @Override
    public void init() throws ServletException {
        // [2] 创建一个 ServletContextTemplateResolver 对象~ resolver: 解析器. 这个对象的功能是从磁盘上加载 html 模板文件.
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(getServletContext());
        // [3] 针对 resolver 对象来设置一些属性
        //     接下来要加载  /WEB-INF/template/ 目录中, 以 .html 结尾的文件, 作为模板引擎.
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");
        // [4] 把 resolver 和 engine 关联起来
        engine.setTemplateResolver(resolver);
    }

    private List<Message> messages = new ArrayList<>();

    // doget 获取到初始页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("messages",messages);
        engine.process("message",webContext,resp.getWriter());
    }

    // dopost 获取到结果页面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        // 1、先读取用户提交数据，并读取到 messages 里面去
        Message message = new Message();
        message.from = req.getParameter("from");
        message.to = req.getParameter("to");
        message.message = req.getParameter("message");
        messages.add(message);
        // 2、返回一个完整页面
        resp.setContentType("text/html;charset=utf8");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("messages",messages);
        engine.process("message",webContext,resp.getWriter());
    }
}
